<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<meta name="viewport"
		content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
	<title>title</title>
	<link rel="stylesheet" type="text/css" href="../css/bootstrap.min.css">
	<link rel="stylesheet" type="text/css" href="../css/api.css" />
	<link rel="stylesheet" type="text/css" href="../css/aui.css" />
	<link rel="stylesheet" type="text/css" href="../css/aui.2.0.css" />
	<link rel="stylesheet" type="text/css" href="../css/icons.css" />
	<script src="../script/jquery-1.9.1.min.js"></script>
	<script src="../script/bootstrap.min.js"></script>
	<style>
		.table tr:first-child {
			background: url(static/img/tableheader-bg.gif) no-repeat left top;
			background-color: #DCE9F2;
			border-top: 1px solid #CBD6DE;
			border-bottom: 1px solid #ADBECB;
			color: #467aa7;
			font-size: 13px;
			font-weight: bold;
		}

		.table {
			margin-bottom: 15px;
			width: 100%;
			border-collapse: collapse;
			font-size: 13px;
			margin-bottom: 15px;
			width: 100%;
			border-collapse: collapse;
		}

		.table td {
			height: 40px;
			text-align: center;
			border: 1px solid #CBD6DE;
			padding: 0;
			margin: 0;
			vertical-align: middle !important;
		}

		body {
			height: auto !important;
		}
	</style>
</head>

<body>
	<header class="aui-bar aui-bar-nav" style="background-color: #03a9f4;position:fixed;" id="header">
		<a class="aui-pull-left aui-btn" tapmode onclick="closeWin();">
			<span class="aui-iconfont aui-icon-left"></span>
		</a>
		<div class="aui-title" id="title">
			容器点检
		</div>
	</header>
	<div class="aui-content" style="margin-top:50px;">
		<div class="aui-form">
			<div class="aui-content aui-margin-b-15">
				<ul class="aui-list aui-form-list" style="font-size: 14px;">
					<li class="aui-list-item">
						<div class="aui-list-item-inner">
							<div class="aui-list-item-label" style="font-size: 14px;">容器条码</div>
							<input type="text" class="aui-input" placeholder="请 扫描/输入 容器条码"
								style="width: 80%;font-size: 14px;" id="ctBarcode">
							<i class="aui-input-addon aui-iconfont aui-icon-scan " style="font-size: 1.6rem"
								onclick="toScanner();"></i>
						</div>
					</li>
					<li class="aui-list-item">
						<div class="aui-list-item-inner">
							<div class="aui-list-item-label" style="font-size: 14px;">执行结果</div>
							<div class="aui-list-item-input">
								<select id="zxResult" style="font-size: 14px;">
									<option value="1">接收</option>
									<option value="2">拒绝接收</option>
								</select>
							</div>
						</div>
					</li>
					<li class="aui-list-item">
						<div class="aui-list-item-inner">
							<div class="aui-list-item-label" style="font-size: 14px;">备注</div>
							<div class="aui-list-item-input">
								<input type="text" class="aui-input" placeholder="请输入备注"
									style="width: 80%;font-size: 14px;" id="remarkValue">
							</div>
						</div>
					</li>
					<div class="aui-content" style="background-color: #ffffff">
						<ul class="aui-list-view aui-grid-view" id="imgslist">
							<li class="aui-list-view-cell aui-img aui-col-xs-4 aui-padded-5" id="addpic"
								onclick="imgClick()">
								<img class="aui-img-object" src="../image/add.jpg">
							</li>
						</ul>
					</div>
				</ul>
			</div>
			<ul id="myTab" class="nav nav-tabs" style="background-color: #F4F4F4;font-size: 13px;">
				<li class="active" style="width: 100%;text-align:center;"> <a href="#item" data-toggle="tab">检修项 </a>

				</li>

			</ul>
			<div id="myTabContent" class="tab-content">
				<div class="tab-pane fade in active" id="item">
					<div style="background-color:white; height: 100%;width: 100%;">
						<table id="chkItemTable" class="table" style="width:200%;">
							<thead id="chkItemTableHead">
							</thead>
						</table>
						<div class="aui-content">
							<div class="aui-btn aui-btn-info" onclick="doSave()" style="width: 100%;height: 100%;">
								<span class="aui-iconfont" style="font-size: 20px;">提交数据</span>

							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="../script/public.js"></script>
<script type="text/javascript" src="../script/hammer.min.js"></script>
<script type="text/javascript" src="../script/clickThrottle.js"></script>
<script>
	var taskCode = "";
	var itemIds = "";
	var itemCodes = "";
	var itemNames = "";
	var itemValues = "";
	var sysidList = "";
	var josnList = [];
	var delItemIds = "";
	var str = "";
	var strHC = "";
	var strYQ = "";
	//检测维修耗材参数
	var HCId = "";
	var mrlGid = "";
	var mrlCode = "";
	var mrlName = "";
	var mrlExName = "";
	var qty = "";
	var measureName = "";
	var consumeType = "";
	var remark = "";
	var josnHCList = [];
	var delHCIds = "";

	//检测维修耗材仪器
	var YqId = "";
	var mrlYqGid = "";
	var mrlYqCode = "";
	var mrlYqName = "";
	var remarkYq = "";
	var josnYqList = [];
	var delYqIds = "";

	var YqIds = "";
	var templateId = ""
	var uiMediaScanner = null;
	var imageFilter = null;
	var imageBrowser = null;

	var citemresult = "";
	var citemList = []

	apiready = function () {
		$("#ctBarcode").focus();
		idSelector = "ctBarcode";
		// 引入多选模块
		uiMediaScanner = api.require('UIMediaScanner');
		// 引入过滤压缩模块
		imageFilter = api.require("imageFilter");
		// 引入图片浏览模块
		imageBrowser = api.require('imageBrowser');

		getUcmChkTaskItem()
	}


	function toScanner() {
		var moduleScanner = api.require('moduleScanner');
		var params = {
			top: 150,//扫描窗口的上边距
			width: 250,//扫描窗口的宽
			height: 250,//扫描窗口的高
			useColor: false,//是否使用自己设定的颜色(startColor和endColor),
			//如果不使用设定的颜色就使用默认的那张网格图
			startColor: '#0F08C8FF',//渐变起始颜色
			endColor: '#7F08C8FF',//渐变结束颜色
			animTime: 2200,//扫描动画时间,单位为毫秒
		};
		moduleScanner.toScannerActivityForResult(params, function (ret, err) {
			if (idSelector == 'ctBarcode') {
				//容器条码
				$("#ctBarcode").val(ret);
				chkCtBarcode(ret);
			}
		});

	}
	$("#ctBarcode").on('keypress', function (e) {
		var keycode = e.keyCode;
		var tm = $(this).val();
		if (keycode == '13') {
			if (tm != null && tm != "" && tm != undefined) {
				$("#ctBarcode").val(tm);
				chkCtBarcode(tm);
			}

		}
	});

	function getUcmChkTaskItem() {
		var serverUrl = localStorage.getItem('serverUrl');
		var url = serverUrl + "/app/getUcmChkTaskItem";
		var un = localStorage.getItem('un');

		var params = new Object();
		params.url = url;
		params.method = 'post';
		params.dataType = 'json';
		params.returnAll = 'false';
		params.timeout = 60;

		var data = {
			values: {
				un: un,
			}
		};

		api.ajax({
			url: url,
			method: 'post',
			dataType: 'json',
			timeout: 300,
			returnAll: false,
			data: data
		}, function (ret, err) {
			if (ret) {
				var data = JSON.stringify(ret);
				var myobj = eval("(" + data + ")");
				//成功
				if (myobj.code == '0') {
					itemIds = "";
					itemCodes = "";
					itemNames = "";
					itemValues = "";
					sysidList = "";
					josnList = [];
					var list = myobj.list;

					templateId = myobj.templateId

					var html = "";
					var html1 = "";
					html1 += "<tr id='tr1' color: #467aa7;>";
					html1 += "<td width='15%' algin='center'>序号</td>";
					html1 += "<td width='30%' algin='center'>点检项</td>";
					html1 += "<td width='25%' algin='center'>检测值</td>";
					html1 += "<td width='30%' algin='center'>备注</td></tr>";

					$api.html($api.byId("chkItemTableHead"), html1);
					str = "";
					if (list != undefined) {
						//遍历
						for (var i = 0; i < list.length; i++) {
							var itemId = list[i].rsItemId;
							var itemCode = list[i].code;
							var itemName = list[i].name;

							if (i == 0) {
								itemIds = itemId;
								itemCodes = itemCode;
								itemNames = itemName;
							} else {
								itemIds = itemIds + "," + itemId;
								itemCodes = itemCodes + "," + itemCode;
								itemNames = itemNames + "," + itemName;
							}

							str += "<tr ><td width='15%' >" + "" + "<input type='text' readonly value='" + (i + 1) + "'></td> <td width='30%' algin='center'>"
								+ itemName + "</td> <td width='25%' algin='left'><select id='"
								+ itemId + 'y' + "'><option value='1' selected='true'>正常</option><option value='2' >异常</option></select></td>"
								+ "<td width='300px' algin='center'><input id='" + itemId + 'x' + "' type='text' value=''></td>"
								+ "</tr>";
						}
					}
					$("#chkItemTableHead").append(str);
				} else if (myobj.code == '1') {
					api.toast({
						msg: myobj.message,
						duration: 3000
					});
				}
			}
		});
	}


	function doSave() {
		if (itemIds != "") {
			var ctBarcode = document.getElementById("ctBarcode").value;

			if (ctBarcode == "" || ctBarcode == null || ctBarcode == undefined) {
				api.toast({
					msg: '容器条码不能为空！',
					duration: 3000
				});
				return;
			}

			//点检项表格中有数据
			setItemValues();
			//提交数据到服务端
			doSubmit();
		} else {
			alert("无点检项信息，无法提交数据");
		}
	}

	function setItemValues() {
		var itemIdArr = itemIds.split(",");//检修项个数
		var itemValue = "";
		var un = localStorage.getItem('un');
		citemresult = ""
		for (i = 0; i < itemIdArr.length; i++) {
			var taskResult = document.getElementById("zxResult").value;

			var itemCodeArr = itemCodes.split(",");
			var itemNameArr = itemNames.split(",");
			var remark = document.getElementById(itemIdArr[i] + "x").value;
			var checkResult = document.getElementById(itemIdArr[i] + "y").value;

			if (checkResult == 2) {
				citemresult = 'N'
				var mode = {
					itemName: itemNameArr[i]
				}
				citemList.push(mode)
			}

			//将点检项的结果转化为jsonList
			var iObj = new itemObj(itemIdArr[i], itemCodeArr[i], itemNameArr[i], checkResult, un, taskResult, remark);
			josnList.push(iObj);
		}
	}


	function itemObj(chkItemId, chkItemCode, chkItemName, checkResult, chkPerson, taskResult, remark) {
		this.chkItemGid = chkItemId;
		this.chkItemCode = chkItemCode;
		this.chkItemName = chkItemName;
		this.checkResult = checkResult;
		this.chkPerson = chkPerson
		this.taskResult = taskResult;
		this.remark = remark;
	}
	function doSubmit() {
		var repairFlag = "N"; //是否维修标识
		var ctBarcode = document.getElementById("ctBarcode").value;
		var type = document.getElementById("zxResult").value;
		var remarkValue = document.getElementById("remarkValue").value;
		if (ctBarcode == "" || ctBarcode == null || ctBarcode == undefined) {
			api.toast({
				msg: '容器条码不能为空！',
				duration: 3000
			});
			return;
		}
		if (type != '2') {
			if (citemresult == "N") {
				api.toast({
					msg: '存在点检项结果为异常，执行结果不能为接收！',
					duration: 3000
				});
				return;
			}
			handleSubmit(repairFlag);
		} else {
			api.confirm({
				title: '提示',
				msg: '是否创建维修工单！',
				buttons: ['确定', '取消']
			}, function (ret, err) {
				repairFlag = ret.buttonIndex == 1 ? "Y" : "N";

				if (repairFlag == "Y" && citemresult != "N") {
					api.toast({
						msg: '不存在异常点检项结果，无法创建维修工单！',
						duration: 3000
					});
					return;
				}
				handleSubmit(repairFlag);
			});
		}
	}
	function handleSubmit(repairFlag) {
		var ctBarcode = document.getElementById("ctBarcode").value;
		var type = document.getElementById("zxResult").value;
		var remarkValue = document.getElementById("remarkValue").value;

		var imgs = document.getElementsByTagName('img');
		var names = [];
		for (var i = 0; i < imgs.length; i++) {
			var img = imgs[i];
			var srcStr = img.getAttribute('src');
			var arrs = srcStr.split('\/');
			var nameStr = arrs[arrs.length - 1];
			if ("add.jpg" != nameStr) {
				names[i] = nameStr;
			}
		}
		var picNames = JSON.parse(JSON.stringify(names));
		var serverUrl = localStorage.getItem('serverUrl');
		var url = serverUrl + "/app/saveUcmChkTaskItem";
		var un = localStorage.getItem('un');

		var params = new Object();
		params.url = url;
		params.method = 'post';
		params.dataType = 'json';
		params.returnAll = 'false';
		params.timeout = 60;

		api.showProgress({
			title: '保存中...',
		});

		var data = {
			values: {
				un: un,
				templateId: templateId,
				ctBarcode: ctBarcode,
				rowData: JSON.stringify(josnList),
				type: type,
				remark: remarkValue,
				picNames: picNames,
				repairFlag: repairFlag,
			}
		};

		api.ajax({
			url: url,
			method: 'post',
			dataType: 'json',
			timeout: 300,
			returnAll: false,
			data: data
		}, function (ret, err) {
			if (ret) {
				var data = JSON.stringify(ret);
				var myobj = eval("(" + data + ")");
				//成功

				console.log( JSON.stringify(myobj))
				if (myobj.code == '0') {

					api.hideProgress();
					api.toast({
						msg: "保存成功",
						duration: 3000
					});

					taskCode = "";
					itemIds = "";
					itemCodes = "";
					itemNames = "";
					itemValues = "";
					sysidList = "";
					josnList = [];
					templateId = "";

					HCIds = "";
					mrlGids = "";
					mrlCodes = "";
					mrlNames = "";
					mrlExNames = "";
					qtys = "";
					measureNames = "";
					consumeTypes = "";
					josnHCList = [];

					YqIds = "";
					mrlYqGids = "";
					mrlYqCodes = "";
					mrlYqNames = "";
					remarkYqs = "";
					josnYqList = [];
					//清空设备扫码框				
					$("#ctBarcode").val("").focus();
					// 清空执行结果					
					$("#zxResult").val("");
					// 清空任务单备注				
					$("#remarkValue").val("");
					//清空点检项表格
					$("#chkItemTableHead").children().remove();
					var imgs = document.getElementsByTagName('img');

					var liElements = document.querySelectorAll('#test'); // 查找所有具有id为'test'的li元素

					// 遍历所有找到的li元素，并从其父元素中移除它们
					liElements.forEach(function (liElement) {
						liElement.parentNode.removeChild(liElement);
					});

					for (var i = 0; i < imgs.length; i++) {
						imgs[i].alt = ''; // 清除图片的 alt 属性值
						// 如果还有其他属性需要清除，可以继续添加类似的语句
					}
					getUcmChkTaskItem()
				} else if (myobj.code == '1') {
					api.hideProgress();
					josnList = [];
					api.toast({
						msg: myobj.message,
						duration: 3000
					});
				}
			} else {
				api.hideProgress();
				alert(JSON.stringify(err));
			}
		});
	}

	function chkCtBarcode() {
		var sm = $("#ctBarcode").val();
		var un = localStorage.getItem('un');
		var serverUrl = localStorage.getItem('serverUrl');
		var url = serverUrl + "/app/searchChkContainer";
		var data = {
			values: {
				sm: sm,
				un: un
			}
		};
		api.ajax({
			url: url,
			method: 'post',
			dataType: 'json',
			timeout: 300,
			returnAll: false,
			data: data
		}, function (ret, err) {
			if (ret) {
				var data = JSON.stringify(ret);
				var myobj = eval("(" + data + ")");
				//返回成功
				if (myobj.code == "0") {

					//失败
				} else if (myobj.code == "1") {
					$("#ctBarcode").val("");
					$("#ctBarcode").select();
					idSelector = "ctBarcode";
					api.toast({
						msg: myobj.message,
						duration: 3000
					});
				}
				api.hideProgress();
			} else {
				$("#ctBarcode").val("");
				$("#ctBarcode").select();
				idSelector = "ctBarcode";
				api.hideProgress();
				alert("连接超时，请耐心等待");
			}
		});
	}

	function imgClick() {
		// 获取图片宽高
		var normalW = $("#addpic img").width();
		api.actionSheet({
			title: '选择图片来源',
			buttons: ['照相机', '浏览相册']
		}, function (ret, err) {
			var index = ret.buttonIndex;
			switch (index) {
				// 拍照
				case 1:
					// 打开拍照
					api.getPicture({
						sourceType: "camera",
						encodingType: "jpg",
						destinationType: "url",
						mediaValue: "pic",
						quality: 50,
						saveToPhotoAlbum: true
					}, function (ret, err) {
						if (ret && ret.data) {
							// 拍照返回的本地路径
							var returnUrl = ret.data;
							// 图片压缩
							imgCompress(returnUrl, 0.5, 0.5, getExt(returnUrl), function (compressImg) {
								var showImgHtml = "<li id='test' class='aui-list-view-cell aui-img aui-col-xs-4  aui-padded-5' style='margin-left: 5px;width:" + normalW + "px;height:" + normalW + "px;' onclick='lookImg(\"" + compressImg + "\")'><img class='aui-img-object' src='" + compressImg +
									"' style='width:" + normalW + "px;height:" + normalW + "px;'></li>";
								// 追加图片
								$("#addpic").before(showImgHtml);
								// ########################################  绑定长按事件 ########################
								addPress($("#imgslist img[src='" + compressImg + "']").parent("li"));

								//上传图片
								uploadFile(compressImg);
							});
						} else {
							api.toast({
								msg: '没有选择，或者选择出错'
							});
						}
					});
					break;
				// 打开图片选择器
				case 2:
					uiMediaScanner.open({
						type: 'picture',
						column: 4,
						classify: true,
						max: 5,
						sort: {
							key: 'time',
							order: 'desc'
						},
						texts: {
							stateText: '已选*项',
							cancelText: '取消',
							finishText: '完成'
						},
						styles: {
							bg: '#fff',
							mark: {
								icon: '',
								position: 'bottom_left',
								size: 20
							},
							nav: {
								bg: '#b23e4b',
								stateColor: '#fff',
								stateSize: 18,
								cancelBg: 'rgba(0,0,0,0)',
								cancelColor: '#fff',
								cancelSize: 18,
								finishBg: 'rgba(0,0,0,0)',
								finishColor: '#fff',
								finishSize: 18
							}
						}
					}, function (ret) {
						if (ret) {
							if (ret.list) {
								for (var i = 0; i < ret.list.length; i++) {
									console.log(i)
									var selectImg = ret.list[i];
									// 获取图片的路径
									var selectimgPath = selectImg.path;
									var selectimgThumbPath = selectImg.thumbPath;
									// 图片压缩
									imgCompress(selectimgPath, 0.5, 0.5, selectImg.suffix, function (compressImg) {
										var showImgHtml = "<li id='test' class='aui-list-view-cell aui-img aui-col-xs-4 aui-padded-5' style='margin-left: 5px;width:" + normalW + "px;height:" + normalW + "px;'  onclick='lookImg(\"" + compressImg + "\")'><img class='aui-img-object' src='" + compressImg +
											"' style='width:" + normalW + "px;height:" + normalW + "px;'></li>";
										// 追加图片
										$("#addpic").before(showImgHtml);
										// ########################################  绑定长按事件 ########################
										addPress($("#imgslist img[src='" + compressImg + "']").parent("li"));

										// ################### 上传图片 #########################
										uploadFile(compressImg);
									});
								}
							}
						}
					});
					break;
			}
		});
	}

	// 为图片添加点击预览功能,排除添加按钮
	function lookImg(compressImg) {
		// 定义一个数组，存储需要预览的图片
		var browerImgs = [];
		// 调用图片预览函数
		browerImgs.push(compressImg);
		openImageBrowser(browerImgs);
	}
	// 图片压缩
	// imgsrc：源图片的路径
	// quality：图片压缩质量，一般建议0.5
	// scale：图片压缩比例，也是建议0.5
	// ext：源图片拓展名
	// callback：转换成功之后回调函数
	function imgCompress(imgsrc, quality, scale, ext, callback) {
		// 压缩文件的保存目录
		var savePath = api.cacheDir + "/" + getNowFormatDate() + "/";
		// 压缩文件生成的随机文件名称
		var savename = NewGuid() + "." + ext;
		imageFilter.compress({
			img: imgsrc,
			quality: quality,
			scale: quality,
			save: {
				album: false,
				imgPath: savePath,
				imgName: savename
			}
		}, function (ret, err) {
			if (ret) {
				callback(savePath + savename);
			} else {
				alert(JSON.stringify(err));
			}
		});
	}

	// 打开图片浏览
	// imgs：需要预览的图片集合
	function openImageBrowser(imgs) {
		imageBrowser.openImages({
			imageUrls: imgs,
			showList: false,
			activeIndex: 0
		});
	}

	// 获取当前的时间，拼接成2015-11-09这样的格式，主要用于对图片进行时间分类
	function getNowFormatDate() {
		var date = new Date();
		var seperator1 = "-";
		var year = date.getFullYear();
		var month = date.getMonth() + 1;
		var strDate = date.getDate();
		if (month >= 1 && month <= 9) {
			month = "0" + month;
		}
		if (strDate >= 0 && strDate <= 9) {
			strDate = "0" + strDate;
		}
		var currentdate = year + seperator1 + month + seperator1 + strDate
		return currentdate;
	}

	// 获取文件拓展名
	function getExt(fileName) {
		return fileName.substring(fileName.lastIndexOf('.') + 1);
	}

	// 生成guid,主要用于生成随机文件名
	function NewGuid() {
		function S4() {
			return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
		}

		return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
	}

	// 添加长按方法
	function addPress(obj, index) {
		// 获取目前长按的对象
		var hammertime = new Hammer(obj[0]);
		// 绑定长按对象
		hammertime.on("press", function (e) {
			api.confirm({
				title: '温馨提示',
				msg: '您确定要删除该图片吗？',
				buttons: ['确定', '取消']
			}, function (ret, err) {
				if (ret.buttonIndex == 1) {
					// 移除自己
					$(obj).remove();
					api.toast({
						msg: '删除成功！'
					});
				}
			});
		});
	}

	// 上传图片
	// url：上传的url地址
	// data：上传的文件
	// callback：上传成功返回地址
	function uploadFile(data) {
		var un = localStorage.getItem('un');
		var serverUrl = localStorage.getItem('serverUrl');
		var url = serverUrl + "/app/uploadPhotosAPP";
		var data = {
			values: {
				un: un
			},
			files: {
				file: data
			}
		};
		api.ajax({
			url: url,
			method: 'post',
			dataType: 'json',
			timeout: 300,
			returnAll: false,
			data: data
		}, function (ret, err) {
			if (ret) {
				var data = JSON.stringify(ret);
				var myobj = eval("(" + data + ")");
				if (myobj.code == "0") {
					console.log("上传成功");
				} else if (myobj.code == "1") {
					alert("上传失败");
				}
			} else {
				alert(JSON.stringify(err));
			}
		});
	}

	//返回按钮
	function closeWin() {
		api.closeWin({});
	}
</script>

</html>